#include <OneWire.h>
#include <DallasTemperature.h>
#define ONE_WIRE_BUS 2
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

#include <LiquidCrystal.h>

//LCD pin to Arduino
const int pin_RS = 8; 
const int pin_EN = 9; 
const int pin_d4 = 4; 
const int pin_d5 = 5; 
const int pin_d6 = 6; 
const int pin_d7 = 7; 
const int pin_BL = 10; 
float tempC=0;

#define RELAY 3

LiquidCrystal lcd( pin_RS,  pin_EN,  pin_d4,  pin_d5,  pin_d6,  pin_d7);

void setup() {
  Serial.begin(9600);
  sensors.begin();
  lcd.begin(16, 2);
  lcd.setCursor(0,0);
  lcd.print("Temp:");
  pinMode(RELAY,OUTPUT);
  digitalWrite(RELAY,HIGH);
}

void loop() {
  temp();
}

void temp()
{
  sensors.requestTemperatures();
  float tempC = sensors.getTempCByIndex(0);
  
  if(tempC != DEVICE_DISCONNECTED_C) 
  {
    
    lcd.print("        ");
    lcd.setCursor(5,0);
    if(tempC >0)
    {  
      lcd.print("+");
      lcd.setCursor(6,0);
      lcd.print(tempC);
    }
    else if(tempC<0)
    {
      lcd.setCursor(5,0);
      lcd.print(tempC);
    }
    else
    {
      lcd.print(" ");
      lcd.setCursor(6,0);
      lcd.print(tempC); 
    }
    if(tempC >=5)  //大于5都启动制冷，可以适当调节到4.x度，提前制冷
    {
      digitalWrite(RELAY,LOW);
      lcd.setCursor(0,1);
      lcd.print("              ");
      lcd.setCursor(0,1);
      lcd.print("start to work");
    }
    else if(tempC<0)  //小于0度关闭制冷，可以适当调节到0.x度，提前关闭制冷
    {
      digitalWrite(RELAY,HIGH);
      lcd.setCursor(0,1);
      lcd.print("              ");  
      lcd.setCursor(0,1);    
      lcd.print("stop work");
    }
  }
  
  else
  {
    lcd.print("        ");
    lcd.setCursor(6,0);
    lcd.print("Error!");
  }
  
}

void Key_Press()
{
  int x;
  x = analogRead (0);
  lcd.setCursor(10,1);
  if (x < 60) {
    lcd.print ("Right ");
  }
  else if (x < 200) {
    lcd.print ("Up    ");
  }
  else if (x < 400){
    lcd.print ("Down  ");
  }
  else if (x < 600){
    lcd.print ("Left  ");
  }
  else if (x < 800){
    lcd.print ("Select");
  }

}
